package com.guli.order.messageQueue;

import com.guli.common.constant.OrderConstant;
import com.guli.common.constant.WareConstant;
import com.guli.common.to.OrderTo;
import com.guli.order.entity.OrderEntity;
import com.guli.order.service.AliPayService;
import com.guli.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;

/*
 * @Author 罗俊
 * @date 2020/11/26 - 3:32 下午
 *
 */

/**
 * 监听队列，取消订单
 */
@Component
@RabbitListener(queues = OrderConstant.ORDER_RELEASE_QUEUE)
@Slf4j
public class CancelOrder {

    @Resource
    OrderService orderService;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    AliPayService aliPayService;

    @RabbitHandler
    public void cancelOrder(OrderEntity orderEntity, Channel channel, Message message) {
        try {
            OrderEntity order = orderService.getById(orderEntity.getId());

            if(ObjectUtils.isEmpty(order)||ObjectUtils.isEmpty(order.getStatus())){
                log.warn("订单id = {}的订单不存在，直接删除消息",orderEntity.getId());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }

            OrderTo orderTo = new OrderTo();

            if (order.getStatus().equals(OrderConstant.Status.WAITING_FOR_PAYMENT)) {

                log.warn("订单id = {}，经过延迟队列之后，仍然是【{}】，即将取消该订单", order.getId(), order.getStatus().getMessage());

                //手动调用支付宝收单（关闭支付宝的支付页面）
                aliPayService.closeAliPay(null,orderEntity.getOrderSn(),OrderConstant.OPERATOR_ID_FOR_ALIPAY);

                OrderEntity orderForUpdating = new OrderEntity();

                orderForUpdating.setStatus(OrderConstant.Status.CLOSED);

                orderForUpdating.setId(order.getId());

                orderService.updateById(orderForUpdating);

                orderTo.setId(order.getId());

                orderTo.setStatus(OrderConstant.Status.CLOSED);
            }



            /**
             * 订单更新之后及时通知库存进行相应的解锁等操作
             * */
            rabbitTemplate.convertAndSend(OrderConstant.ORDER_EVENT_EXCHANGE, WareConstant.STOCK_RELEASE_CANCEL_ORDER_ROUTING_KEY,orderTo);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }

            e.printStackTrace();
        }

    }

}
